package net.kazed.nextaction.context.activity;

import android.app.ListActivity;
import android.content.ContentUris;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import net.kazed.nextaction.NextActionApplication;
import net.kazed.nextaction.R;
import net.kazed.nextaction.database.ContextCache;
import net.kazed.nextaction.database.GtdContext;
import net.kazed.nextaction.database.Task;
import net.kazed.nextaction.database.TreeNode;

public class ContextView2Activity extends ListActivity {

   private static final String cTag = "ContextView2Activity";
	
   private static final int MENU_INSERT_CONTEXT = Menu.FIRST + 1;
   private static final int MENU_INSERT_TASK = Menu.FIRST + 2;
   private static final int MENU_DELETE_CONTEXT = Menu.FIRST + 3;
   
   private static final int NEW_TASK = 1;
   private static final int EDIT_TASK = 2;
   private static final int VIEW_TASK = 3;
   private static final int VIEW_CONTEXT = 4;
   private static final int NEW_CONTEXT = 5;

	private TextView titleWidget;
   private TextView numberOfTasksText;
   private Button button;
//   private ListView contextList;
//   private ListView taskList;
//   private TextView noTasksMessageView;
   
	private long contextId;
	private Uri contextUri;
	private GtdContext context;
   private Cursor taskCursor;
   private int taskCount;
   private ContextCache contextCache;
   private ContextTaskListAdapter listAdapter;

	@Override
    public void onCreate(Bundle icicle) {
		contextUri = getIntent().getData();
      setContentView(R.layout.context_task_list);
      setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
      
      titleWidget = (TextView) findViewById(R.id.context_name);
      numberOfTasksText = (TextView) findViewById(R.id.number_of_tasks);
      button = (Button) findViewById(R.id.edit_button);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Intent intent = new Intent(ContextView2Activity.this, ContextEditorActivity.class);
            intent.setAction(Intent.ACTION_EDIT);
            intent.setData(contextUri);
            startActivity(intent);
         }
      });
      
      contextId = ContentUris.parseId(contextUri);
      
      taskCursor = managedQuery(Task.CONTENT_URI, Task.FULL_PROJECTION.getFieldNames(),
            Task.CONTEXT_ID + " = ?", new String[] {String.valueOf(contextId)}, 
            Task.CREATED_DATE + " ASC");
      
      NextActionApplication application = (NextActionApplication) getApplication();
      contextCache = application.getContextCache();
      listAdapter = new ContextTaskListAdapter(contextCache, (int) contextId, taskCursor);
      setListAdapter(listAdapter);
      
      super.onCreate(icicle);
	}
	
	@Override
	protected void onResume() {
	   context = contextCache.getContextTree((int) contextId).getData();
//      Cursor contextItemCursor = getContentResolver().query(contextUri, GtdContext.FULL_PROJECTION.getFieldNames(),
//            null, null, null);
//      if (contextItemCursor.moveToFirst()) {
//         context = new GtdContext(contextItemCursor);
//      }
//      contextItemCursor.close();

      titleWidget.setText(context.getAbsoluteContextPath(getContentResolver(), " > "));
      numberOfTasksText.setText(Integer.toString(context.getNumberOfTasks()));

		super.onResume();
	}

   @Override
   protected void onListItemClick(ListView l, View v, int position, long id) {
      Object item = listAdapter.getItem(position);
      if (item instanceof GtdContext) {
         GtdContext context = (GtdContext) item;
         Uri itemUri = ContentUris.withAppendedId(GtdContext.CONTENT_URI, context.getId());
         Intent intent = new Intent(Intent.ACTION_VIEW, itemUri);
         startActivityForResult(intent, VIEW_CONTEXT);
      } else if (item instanceof Task) {
         Task task = (Task) item;
         Uri itemUri = ContentUris.withAppendedId(Task.CONTENT_URI, task.getId());
         Intent intent = new Intent(Intent.ACTION_VIEW, itemUri);
         startActivityForResult(intent, VIEW_TASK);
      }
   }

   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      taskCursor.requery();
      taskCount = taskCursor.getCount();
   }

   /**
     * {@inheritDoc}
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
       Resources resources = getResources();
       menu.add(0, MENU_INSERT_TASK, 0, resources.getString(R.string.menu_add_task))
          .setIcon(android.R.drawable.ic_menu_add).setAlphabeticShortcut('a');
       menu.add(0, MENU_INSERT_CONTEXT, 1, resources.getString(R.string.menu_add_context))
          .setIcon(android.R.drawable.ic_menu_add).setAlphabeticShortcut('c');
       menu.add(0, MENU_DELETE_CONTEXT, 2, resources.getString(R.string.menu_delete_context))
          .setIcon(android.R.drawable.ic_menu_delete).setAlphabeticShortcut('d');
       return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       switch (item.getItemId()) {
       case MENU_INSERT_TASK:
          Intent intent = new Intent(Intent.ACTION_INSERT, Task.CONTENT_URI); // new Intent(Intent.ACTION_INSERT, uri);
          intent.putExtra(GtdContext.SELECTED_CONTEXT_ID, contextId);
          startActivityForResult(intent, NEW_TASK);
          break;
       case MENU_INSERT_CONTEXT:
          Intent contextIntent = new Intent(Intent.ACTION_INSERT, contextUri);
//          contextIntent.putExtra(GtdContext.SELECTED_CONTEXT_ID, contextId);
          startActivityForResult(contextIntent, NEW_CONTEXT);
          break;
       case MENU_DELETE_CONTEXT:
          // TODO update all tasks contained in this context, remove contextId
          getContentResolver().delete(contextUri, null, null);
          finish();
          break;
       }
       return super.onOptionsItemSelected(item);
    }

    private static class ContextTaskListAdapter implements ListAdapter {

      private Integer contextId;
      private Cursor taskCursor;
      private int numberOfContexts;
      private int firstTaskPosition;
      private TreeNode<GtdContext> contextNode;

      /**
       * Constructor.
       * @param contextId Parent context ID.
       * @param taskCursor Cursor for retrieving tasks.
       */
      public ContextTaskListAdapter(ContextCache contextCache, Integer contextId, Cursor taskCursor) {
        this.contextId = contextId;
        this.taskCursor = taskCursor;
        firstTaskPosition = 2;
        contextNode = contextCache.getContextTree(contextId);
        numberOfContexts = contextNode.getChildren().size();
      }
       
      @Override
      public boolean areAllItemsEnabled() {
         return false;
      }

      @Override
      public boolean isEnabled(int position) {
         Log.d(cTag, "isEnabled: " + position);
         return isContextItem(position) || isTaskItem(position);
      }

      @Override
      public int getCount() {
         return numberOfContexts + taskCursor.getCount() + 2;
      }

      @Override
      public Object getItem(int position) {
         // TODO Auto-generated method stub
         Log.d(cTag, "getItem: " + position);
         Object item = null;
         if (isContextItem(position)) {
            GtdContext context = contextNode.getChildren().get(position - 1).getData();
            item = context;
         } else if (isTaskItem(position)) {
            taskCursor.moveToPosition(position - numberOfContexts - 2);
            Task task = new Task(taskCursor);
            item = task;
         }
         return item;
      }

      @Override
      public long getItemId(int position) {
         // TODO Auto-generated method stub
         Log.d(cTag, "getItemId: " + position);
         long itemId = 0;
         if (isContextItem(position)) {
            GtdContext context = contextNode.getChildren().get(position - 1).getData();
            itemId = context.getId();
         }

         return itemId;
      }

      @Override
      public int getItemViewType(int position) {
         int viewType = 0;
         Log.d(cTag, "getItemViewType: " + position);
//         if (isContextItem(position)) {
//            viewType = R.layout.context_list_item_view;
//         } else if (isTaskItem(position)) {
//            viewType = R.layout.task_list_item_view;
//         }
         return viewType;
      }

      @Override
      public View getView(int position, View convertView, ViewGroup parent) {
         View view = null;
         
         Log.d(cTag, "getView: " + position);
         
         if (position == 0) {
            TextView textView = null;
            if (convertView instanceof TextView) {
               textView = (TextView) convertView;
            } else {
               textView = new TextView(parent.getContext());
            }
            textView.setText("Contexts");
            view = textView;
         } else if (isContextItem(position)) {
            ContextListItemView contextView = null;
            if (convertView instanceof ContextListItemView) {
               contextView = (ContextListItemView) convertView;
            } else {
               contextView = new ContextListItemView(parent.getContext(), R.layout.context_list_item_view);
            }
            GtdContext context = contextNode.getChildren().get(position - 1).getData();
            contextView.updateView(context);
            view = contextView;
         } else if (position == numberOfContexts + 1) {
            TextView textView = null;
            if (convertView instanceof TextView) {
               textView = (TextView) convertView;
            } else {
               textView = new TextView(parent.getContext());
            }
            textView.setText("Tasks");
            view = textView;
         } else if (isTaskItem(position)) {
            TaskListItemView taskView = null;
            if (convertView instanceof TaskListItemView) {
               taskView = (TaskListItemView) convertView;
            } else {
               taskView = new TaskListItemView(parent.getContext());
            }
            taskCursor.moveToPosition(position - numberOfContexts - 2);
            Task task = new Task(taskCursor);
            taskView.updateView(task);
            view = taskView;
         } else {
            Log.d(cTag, "unknown view");
         }
         
         return view;
      }

      @Override
      public int getViewTypeCount() {
         return 3;
      }

      @Override
      public boolean hasStableIds() {
         return false;
      }

      @Override
      public boolean isEmpty() {
         return false;
      }

      @Override
      public void registerDataSetObserver(DataSetObserver observer) {
         // TODO Auto-generated method stub
         
      }

      @Override
      public void unregisterDataSetObserver(DataSetObserver observer) {
         // TODO Auto-generated method stub
         
      }
       
      private boolean isContextItem(int position) {
         return (position > 0 && position <= numberOfContexts);
      }

      private boolean isTaskItem(int position) {
         return (position >= firstTaskPosition);
      }

    }

}
